<template>
	<view class="orderInfoPage">
		<u-navbar :autoBack="true" bgColor="#fff">
			<view slot="center">
				订单详情
			</view>
		</u-navbar>

		<view class="address-info" :style="{background:`url(${imgUrl}addressBg.png) no-repeat`}" @tap="goMyaddress">
			<view class="left">
				<view class="top">
					<h2>{{pitchAddress.name || ''}}</h2>
					<span>{{pitchAddress.mobile || ''}}</span>
					<span v-if="!pitchAddress.id">请选择地址</span>
					<u-icon name="arrow-right" size="16" color="#000"></u-icon>
				</view>
				<view class="btm" v-if="pitchAddress.id">
					<u-icon name="map" color="#000" size="13"></u-icon>
					{{pitchAddress.province || ''}}{{pitchAddress.city || ''}}{{pitchAddress.district || ''}}{{pitchAddress.detailedAddress || ''}}
				</view>
			</view>
		</view>

		<view class="goodsInfo">
			<view class="" v-for="(item,index) in orderInfo" :key="index">
				<view class="infoTitle" v-if="item.shopName">
					{{item.shopName}}
				</view>
				<view class="shopListBox">
					<view class="shopItem flex_heng" v-for="(items,indexs) in item.goodsInfo" :key="indexs">
						<view class="shopLeft flex_heng">
							<image :src="items.img" mode="" class="shopImg"></image>
							<view class="shopMid flex_shu">
								<view class="shopName u-line-1">
									{{items.goodsName}}
								</view>
								<view class="shopSku u-line-2">
									{{items.sku}}
								</view>
							</view>
						</view>
						<view class="shopRight flex_shu">
							<view class="shopPrice">
								<text>￥</text>{{items.price}}
							</view>
							<view class="shopNum">
								×{{items.num}}
							</view>
						</view>
					</view>
				</view>

				<view class="shopBtm flex_heng">
					<view class="totalText">
						合计
					</view>
					<view class="totalPrice">
						<text>￥{{ item.totalPrice ? item.totalPrice.toString().split('.')[0] : '0' }}</text>
						<text
							style="font-size:28rpx">.{{ item.totalPrice && item.totalPrice.toString().includes('.') ? item.totalPrice.toString().split('.')[1] : '00' }}</text>
					</view>
				</view>

			</view>
		</view>

		<view class="shopCoupon" v-if="couponList.length>0">
			<view class="title flex_heng">
				<image :src="imgUrl + 'logo.png'" mode="" class="logoImg"></image>
				<view class="titleText">
					红星美凯龙
				</view>
			</view>
			<view class="couponListBox">
				<view class="couponItem" v-for="(item,index) in couponList" :key="index">
					<view class="couponItemCon">
						<image :src="imgUrl + 'couponBg1.png'" mode=""></image>
						<view class="itemAmount">
							￥{{item.discountAmount}}
						</view>
						<view class="itemName">
							{{item.name}}
						</view>
						<view class="itemType">
							满{{item.conditionAmount}}减{{item.discountAmount}}
						</view>
						<view class="xuanze" @tap.stop="toggleGoodsSelect(index)">
							<radio value="r1" :checked="selectedGoodsIndexes.includes(index)" color="#FF5252"
								style="transform:scale(0.7)" />
						</view>
					</view>
				</view>
			</view>
			<!-- 			<view class="couponListBox" v-else>
				<u-empty mode="coupon" icon="http://cdn.uviewui.com/uview/empty/coupon.png">
				</u-empty>
			</view> -->
		</view>


		<view class="midBox flex_heng" v-if="false">
			<view class="leftTitle">
				定/销货单
			</view>
			<view class="rightText" @tap="viewSalesOpen">
				查看
			</view>
		</view>

		<view class="form-box" v-if="false">
			<view class="item-li">
				<text style="font-size: 24rpx;">商品总价</text>
				<view class="right">
					￥{{discountsPrice}}
				</view>
			</view>
			<view class="item-li">
				<text class="label">运费</text>
				<view class="right">
					<text class="ipt">￥0</text>
				</view>
			</view>
			<view class="item-li">
				<text class="label">优惠金额</text>
				<view class="right">
					<text class="ipt">￥{{orderInfo.discountPrice}}</text>
				</view>
			</view>
			<view class="item-li">
				<text class="label">需付款</text>
				<view class="right">
					<text style="color: #F21331;">￥{{discountsPrice}}</text>
				</view>
			</view>
			<view class="item-li">
				<text class="label">订单编号</text>
				<view class="right">
					<text class="ipt">{{orderInfo.waterNumber}}</text>
					<text class="ipt line"> | </text>
					<text class="ipt copy" @click="copy(orderInfo.waterNumber)">复制</text>
				</view>
			</view>
			<view class="item-li">
				<text class="label">下单时间</text>
				<view class="right">
					<text class="ipt">{{orderInfo.createTime}}</text>
				</view>
			</view>
		</view>

		<view class="footer flex_heng">
			<view class="footerLeft">
				应付:<text>￥{{ payMoney ? payMoney.toString().split('.')[0] : '0' }}</text>
				<text
					style="font-size:28rpx">.{{ payMoney && payMoney.toString().includes('.') ? payMoney.toString().split('.')[1] : '00' }}</text>
			</view>
			<view class="hollow" @click="queren">提交订单</view>
		</view>


		<u-popup :show="salesOpen" mode="center" @close="close" @open="open" :round="10" :safeAreaInsetBottom="false">
			<view class="phoneBox flex_shu">
				<view class="phoneTitle">
					定/销货单
				</view>
				<view class="tableBox">
					<tableComponent :thead="options.thead" :tbody="options.tbody"></tableComponent>
				</view>

				<view class="btnBox flex_heng">
					<view class="closeBtn" @tap="close()">
						取消
					</view>
					<view class="phoneBtn" @tap="queren()" v-if="querenState">
						确认下单
					</view>
					<view class="phoneBtn" @tap="queren()" v-else>
						确认
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		initiatePay,
		getAddressList,
		createOrder,
		getOrderListDetails,
		isCouponUse
	} from '@/api/api.js'
	import tableComponent from '@/components/table/table.vue'
	export default {
		components: {
			tableComponent
		},
		data() {
			return {
				options: {
					operation: [],
					thead: [{
						name: '商品名称',
						prop: 'goodsName',
					}, {
						name: '规格',
						prop: 'sku',
					}, {
						name: '零售价',
						prop: 'price',
					}, {
						name: '数量',
						prop: 'num',
					}],
					tbody: [],
				},
				imgUrl: this.$imgUrl,
				show: true,
				orderInfo: [],
				// 选中的地址信息
				pitchAddress: {},
				productList: [],
				waterNumber: "", // 订单流水号
				couponList: [],
				couponPrice: 0,
				orderId: null,

				selectedGoodsIndexes: [],
				discountId: '',
				salesOpen: false,
				querenState: false,
			}
		},
		onLoad(op) {
			console.log(op);
			if (op.orderId) {
				this.orderId = op.orderId;
				this.getOrderInfo()
			} else {
				this.orderInfo = uni.getStorageSync('orderInfo');
			}
		},
		computed: {
			discountsPrice() {
				let total = 0;
				if (this.productList.length === 0) return 0
				this.productList.forEach(item => {
					total += item.discountsPrice
				})
				return total
			}
		},

		onShareAppMessage(e) {
			console.log(e);
		},
		onShow() {
			this.getpitchAddress()
			this.getUserCouponListData()
		},
		// 计算属性保持不变
		computed: {
			payMoney() {
				const total = this.orderInfo.reduce((sum, item) => sum + item.totalPrice, 0);
				return total - this.couponPrice;
			}
		},

		methods: {
			viewSalesOpen() {
				this.options.tbody = [].concat(...this.orderInfo.map(shop => shop.goodsInfo));
				console.log('this.options.tbody', this.options.tbody);
				this.salesOpen = true;
			},
			queren() {
				if (!this.querenState) {
					this.querenState = true;
					this.salesOpen = false;
				} else {
					const params = {
						discountId: this.discountId,
						addressId: this.pitchAddress.id,

						shoppingCartIdList: this.orderInfo.some(order =>
								order.goodsInfo.some(good => good.shoppingCartId)
							) ?
							this.orderInfo.flatMap(order =>
								order.goodsInfo
								.filter(good => good.shoppingCartId)
								.map(good => good.shoppingCartId)
							) : [],


						skuList: this.orderInfo.flatMap(order => order.goodsInfo.map(good => ({
							num: good.num,
							skuId: good.skuId
						})))
					};
					createOrder(params).then(res => {
						console.log('创建订单', res);

						// 提示支付成功
						uni.showToast({
							title: '下单成功',
							icon: 'success'
						})

						setTimeout(() => {
							uni.removeStorageSync('orderInfo');
							uni.reLaunch({
								url: '/pages/package/orderManagement/orderManagement'
							})
						}, 1000)
					})
				}
				// this.querenState = true;

			},
			open() {
				this.salesOpen = true;
			},
			close() {
				this.salesOpen = false;
			},

			// 切换优惠券选中状态
			toggleGoodsSelect(index) {
				const i = this.selectedGoodsIndexes.indexOf(index)
				if (i > -1) {
					this.selectedGoodsIndexes.splice(i, 1)
				} else {
					this.selectedGoodsIndexes.push(index)
				}

				// 新增：根据选中的优惠券更新 couponPrice
				const selectedCoupons = this.selectedGoodsIndexes.map(idx => this.couponList[idx])
				console.log('selectedCoupons', selectedCoupons)
				this.discountId = selectedCoupons[0].id
				this.couponPrice = selectedCoupons.reduce((sum, coupon) => sum + (coupon?.discountAmount || 0), 0)
			},

			//测可使用优惠券
			getUserCouponListData() {
				let newList = [];
				console.log('this.orderInfo.goodsInfo', this.orderInfo)
				this.orderInfo.map(item => {
					item.goodsInfo.map(items => {
						newList.push(items.skuId)
					})
				})
				isCouponUse(newList).then(res => {
					if (res.code == 200) {
						console.log(res);
						this.couponList = res.data
					}
				})
			},
			//创建订单
			submitOrder() {
				if (this.querenState) {
					const params = {
						discountId: this.discountId,
						addressId: this.pitchAddress.id,

						shoppingCartIdList: this.orderInfo.some(order =>
								order.goodsInfo.some(good => good.shoppingCartId)
							) ?
							this.orderInfo.flatMap(order =>
								order.goodsInfo
								.filter(good => good.shoppingCartId)
								.map(good => good.shoppingCartId)
							) : [],


						skuList: this.orderInfo.flatMap(order => order.goodsInfo.map(good => ({
							num: good.num,
							skuId: good.skuId
						})))
					};
					createOrder(params).then(res => {
						console.log('创建订单', res);
						uni.removeStorageSync('orderInfo');
						uni.reLaunch({
							url: '/package/pages/orderManagement/orderManagement'
						})
					})
				} else {
					this.querenState = true;
					this.viewSalesOpen();
				}
			},
			//获取地址列表
			getpitchAddress() {
				uni.showLoading()
				getAddressList().then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						console.log(res);
						this.pitchAddress = res.rows[0]
					}
				})
			},

			//去地址列表
			goMyaddress() {
				uni.navigateTo({
					url: '/pages/package/myAddress/myAddress'
				})
			},

			//订单详情
			getOrderInfo() {
				uni.showLoading()
				getOrderListDetails(this.orderId).then(res => {
					uni.hideLoading()
					console.log('订单详情', res)
					this.orderInfo = res.data;

					this.options.tbody = res.data.goodsInfo
				})
			},

			// 复制
			copy() {
				uni.setClipboardData({
					data: this.waterNumber,
					success: function() {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					}
				});
			},


			//商品详情
			goGoodInfo(item) {
				uni.navigateTo({
					url: `/package/goodsDetail/goodsDetail?id=${item.id}`
				})
			},
		}
	}
</script>

<style lang="scss">
	.orderInfoPage {
		width: 100%;
		min-height: 100vh;
		background-color: #F6F6F6;
		padding: 200rpx 28rpx 28rpx;
		box-sizing: border-box;

		.phoneBox {
			padding: 34rpx;
			box-sizing: border-box;
			font-family: "Alibaba PuHuiTi 2.0";
			width: 680rpx;

			.phoneTitle {
				color: #000000;
				font-size: 36rpx;
				font-weight: 500;
			}

			.tableBox {
				margin-top: 20rpx;
				width: 100%;
			}

			.btnBox {
				width: 100%;
				height: 76rpx;
				margin-top: 68rpx;

				.closeBtn {
					width: 212rpx;
					height: 76rpx;
					line-height: 76rpx;
					border-radius: 278rpx;
					border: 2rpx solid #666666;
					color: #000000;
					text-align: center;
					font-size: 32rpx;
					font-weight: 500;
				}

				.phoneBtn {
					width: 212rpx;
					height: 76rpx;
					line-height: 76rpx;
					border-radius: 278rpx;
					opacity: 1;
					background: #1078f9;
					color: #fff;
					text-align: center;
					font-size: 32rpx;
					font-weight: 500;
				}
			}
		}


		.address-info {
			width: 100%;
			background-size: 100% 100% !important;
			padding: 38rpx 20rpx;
			box-sizing: border-box;
			border-radius: 27rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				width: 100%;

				.top {
					display: flex;
					align-items: center;
					font-size: 26rpx;
					font-family: "Alibaba PuHuiTi 2.0";

					h2 {
						color: #000;
						font-size: 32rpx;
						margin: 0 6rpx;
					}

					span {
						color: #000;
						font-size: 32rpx;
					}
				}

				.btm {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					margin-top: 20rpx;
					color: #999;
					font-weight: 400;
					font-family: "Alibaba PuHuiTi 2.0";
				}
			}
		}

		.goodsInfo {
			width: 100%;
			border-radius: 16rpx;
			background: #ffffff;
			margin-top: 28rpx;
			padding: 28rpx;
			box-sizing: border-box;

			.infoTitle {
				color: #000000;
				font-size: 28rpx;
				font-weight: 500;
			}

			.shopListBox {

				.shopItem {
					margin: 28rpx 0 0 0;
					height: 124rpx;

					.shopLeft {
						justify-content: flex-start;

						.shopImg {
							width: 124rpx;
							height: 124rpx;
							border-radius: 16rpx;
						}

						.shopMid {
							margin-left: 16rpx;
							height: 124rpx;
							align-items: flex-start;
							justify-content: flex-start;
							font-family: "Alibaba PuHuiTi 2.0";

							.shopName {
								color: #000000;
								font-size: 28rpx;
								font-weight: 500;
							}

							.shopSku {
								color: #666666;
								font-size: 24rpx;
								font-weight: 400;
								margin-top: 8rpx;
							}
						}
					}

					.shopRight {
						height: 124rpx;
						align-items: flex-end;
						justify-content: space-between;

						.shopPrice {
							color: #000000;
							font-weight: 700;
							font-size: 36rpx;

							text {
								font-size: 28rpx;
							}
						}

						.shopNum {
							color: #666666;
							font-size: 28rpx;
							font-weight: 400;
						}
					}
				}
			}

			.shopBtm {
				margin-top: 28rpx;

				.totalText {
					color: #000000;
					font-size: 24rpx;
					font-weight: 400;
				}

				.totalPrice {
					color: #000000;
					font-size: 36rpx;
					font-weight: 700;
				}
			}
		}

		.shopCoupon {
			margin-top: 28rpx;
			width: 100%;
			border-radius: 16rpx;
			background: #ffffff;
			padding: 28rpx;
			box-sizing: border-box;

			.title {
				width: 100%;
				height: 76rpx;
				justify-content: flex-start;

				.logoImg {
					width: 76rpx;
					height: 76rpx;
				}

				.titleText {
					margin-left: 16rpx;
					color: #000000;
					font-size: 32rpx;
					font-weight: 500;
					font-family: "Alibaba PuHuiTi 2.0";
				}
			}

			.couponListBox {
				width: 100%;

				.couponItem {
					width: 100%;
					height: 106rpx;
					margin-top: 28rpx;

					.couponItemCon {
						width: 100%;
						height: 106rpx;
						position: relative;

						image {
							width: 100%;
							height: 100%;
							position: absolute;
							top: 0;
							lefr: 0;
						}

						.itemAmount {
							position: absolute;
							top: 50%;
							left: 18rpx;
							transform: translateY(-50%);
							color: #ff2424;
							font-size: 32rpx;
							font-weight: 500;
							font-family: "Alibaba PuHuiTi 2.0";
						}

						.itemName {
							position: absolute;
							top: 16rpx;
							left: 162rpx;
							color: #ff0000;
							font-size: 28rpx;
							font-weight: 500;
							font-family: "Alibaba PuHuiTi 2.0";
						}

						.itemType {
							position: absolute;
							top: 60rpx;
							left: 162rpx;
							color: #787878;
							text-align: left;
							font-size: 22rpx;
							font-weight: 300;
							font-family: "Alibaba PuHuiTi 2.0";
						}

						.xuanze {
							position: absolute;
							top: 50%;
							right: 28rpx;
							transform: translateY(-50%);
							opacity: 1;
							color: #ffffff;
							text-align: center;
							font-size: 24rpx;
							font-weight: 500;
							font-family: "Alibaba PuHuiTi 2.0";
						}

					}

				}
			}

		}

		.midBox {
			width: 100%;
			margin-top: 28rpx;
			padding: 28rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-radius: 16rpx;
			background: #ffffff;

			.leftTitle {
				font-size: 26rpx;
				color: #000000;
			}

			.rightText {
				font-size: 26rpx;
				color: #1078F9;
			}
		}

		.form-box {
			width: 100%;
			margin-top: 28rpx;
			padding: 28rpx 8rpx;
			box-sizing: border-box;

			.title {
				font-size: 26rpx;
				color: #000000;
			}

			.line {
				margin: 0 8rpx;
			}

			.copy {
				color: #8551EB;
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			right: 0;
			width: 100%;
			display: flex;
			align-items: center;
			font-family: "Alibaba PuHuiTi 2.0";
			padding: 28rpx 36rpx 68rpx;
			box-sizing: border-box;
			background-color: #fff;

			.footerLeft {
				color: #000000;
				font-size: 24rpx;
				font-weight: 700;

				text {

					font-size: 36rpx;
				}
			}

			.hollow {
				width: 214rpx;
				height: 74rpx;
				line-height: 74rpx;
				border-radius: 150rpx;
				background: #ff1e1e;
				color: #ffffff;
				font-size: 28rpx;
				font-weight: 500;
				font-family: "Alibaba PuHuiTi 2.0";
				text-align: center;
			}

		}
	}



	.bttitle {
		display: flex;

		.nav-title {
			width: 100%;
			text-align: center;
		}
	}
</style>